import wsgiref.handlers

from google.appengine.ext import db
from google.appengine.ext import webapp

import models
import datetime

def convertToFloat(value):
  """Return Float, if ValueError return 0"""
  try:
    return float(value)
  except ValueError:
    return 0

class PutPosition(webapp.RequestHandler):
  def get(self):
    """ Take mlong, mlat, mid and mdata and store values in DataStore """

    # Process input values, take 0 as default if missing
    deviceId = self.request.get('mid', 0)
    deviceLat = self.request.get('mlat', 0)
    deviceLong = self.request.get('mlon', 0)
    deviceData = self.request.get('mdata', 0)

    # Convert values to the format we need
    try:
      deviceIdTuple = deviceId.partition('_')
    except AttributeError:
      self.response.headers['Content-Type'] = 'text/plain'
      self.response.out.write('Device ID malformed; location NOT PUT')
      return None
    deviceId = deviceIdTuple[0]
    try:
      deviceGroupAndLetter = deviceIdTuple[2].partition('_')
      deviceGroup = deviceGroupAndLetter[0]
      deviceLetter = deviceGroupAndLetter[2]
    except AttributeError:
      #TODO: Fine spare, unused, letter here
      deviceLetter = "Z"
      deviceGroup = deviceIdTuple[2]
    try:
      deviceDataTuple = deviceData.partition('km')
    except:
      deviceDataTuple = ("", "")
    deviceSpeed = convertToFloat(deviceDataTuple[0])
    deviceLat = convertToFloat(deviceLat)
    deviceLong = convertToFloat(deviceLong)
    latLongString = ('%f,%f' % (deviceLat, deviceLong))
    
    # Insert values into Location DataStore
    myCurrentPosition = models.Location()
    myCurrentPosition.deviceId = deviceId
    myCurrentPosition.location = (latLongString)
    myCurrentPosition.dateTime = datetime.datetime.now()
    myCurrentPosition.speed = deviceSpeed
    myCurrentPosition.group = deviceGroup
    myCurrentPosition.put()

    # Check this deviceId is a member of GroupId in the Groups DataStore, if not add it
    # [this saves enormous selects every time in /get ]
    groups = models.Device()
    groupQuery = db.GqlQuery("SELECT * FROM Device WHERE deviceId = '%s' AND groupId = '%s'" % (deviceId, deviceGroup))
    result = groupQuery.fetch(1)
    try:
      result[0]
    except IndexError:
      groups.deviceId = deviceId
      groups.groupId = deviceGroup
      groups.letterIdentifier = deviceLetter
      groups.put()

    # Return very little to browser to keep data usage down
    self.response.headers['Content-Type'] = 'text/plain'
    #self.response.out.write('1')
    self.response.out.write('4X-84.81445312Y43.6837635X-84.77050781Y43.4529188X-84.18823242Y43.4848121X-84.15527343Y43.8186748X
NA
NA
off')


def main():
  """Pass PUT requests to relevant methods"""
  application = webapp.WSGIApplication(
                                       [
                                         ('/getBBpoly.asp', PutPosition)
                                       ],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
